#include <func.h>
#include "head.h"

int recvn(int netFd, void *p, int n);
int download(MYSQL *db, char *argv, int netFd){
    //gets path //gets /usr1/file1
    //格式:gets 绝对路径(用户视角)
    char arr[100] = "";
    strcpy(arr, argv);
    char *command = strtok(arr, " ");
    char *file_name = strtok(NULL, " ");  // file_name: /usr1/file1
    // char filePath[100] = {0};
    // sprintf(filePath, ".%s", fileName);
    // printf("filePath = %s\n", filePath);
    char md5[100] = {0};
    int gret = getMd5FromFileName(db, file_name, md5);
    if(gret == -1){
        send(netFd, "0", 1, MSG_NOSIGNAL);
        return 0;
    }
    char realPath[1024] = {0};
    sprintf(realPath, "./Catalog/%s", md5);
    int fd = open(realPath, O_RDWR);
    if(fd == -1){
        printf("fd = %d", fd);
        send(netFd, "0", 1, MSG_NOSIGNAL);
        return 0;
    }
    else{
        send(netFd, "1", 1, MSG_NOSIGNAL);
    }
    struct stat statbuf;
    fstat(fd, &statbuf);
    //用小火车发送文件大小
    train_t t;
    t.dataLength = sizeof(statbuf.st_size);
    memcpy(t.buf, &statbuf.st_size, sizeof(statbuf.st_size));
    send(netFd, &t, sizeof(t.dataLength) + t.dataLength, MSG_NOSIGNAL);

    //收到客户端发送的消息，判断是否需要继续发送文件
    char buf[1024] = {0};
    recv(netFd, buf, 1, 0);
    if(strcmp(buf, "1") == 0){//说明文件已经被客户端下载完全
        // bzero(buf, sizeof(buf));
        // sprintf(buf, "%s%s", pwd, "$");
        // send(netFd, buf, strlen(buf), MSG_NOSIGNAL);
        return 0;
    }
    //客户端尚未下载或未下载完全
    long sizeFromClient;
    recvn(netFd, &sizeFromClient, sizeof(sizeFromClient));
    //获得客户端中文件长度
    lseek(fd, sizeFromClient, SEEK_SET);
    char *p = (char *)mmap(NULL, statbuf.st_size - sizeFromClient, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    send(netFd, p, statbuf.st_size - sizeFromClient, MSG_NOSIGNAL);
    munmap(p, statbuf.st_size - sizeFromClient);
    // bzero(buf, sizeof(buf));
    // sprintf(buf, "%s%s", pwd, "$");
    // send(netFd, buf, strlen(buf), MSG_NOSIGNAL);
    close(fd);
}
//客户端下载文件，服务端给客户端发送文件（实现断点续传）

int recvn(int netFd, void *p, int n){
    int total = 0;
    int ret;
    char *pTmp = (char *)p;
    while(total < n){
        ret = recv(netFd, pTmp + total, n - total, 0);
        ERROR_CHECK(ret, -1, "recv");
        total += ret;
    }
    return 0;
}
